package com.leetcode.题库;

/**
 * @author 覃国强
 * @date 2022-03-16 20:06
 */
public class 题库_0209_长度最小的子数组 {

  static
  class Solution {
    public int minSubArrayLen(int target, int[] nums) {
      if (nums == null || nums.length == 0) {
        return 0;
      }
      if (nums[0] >= target) {
        return 1;
      }
      int answer = Integer.MAX_VALUE;
      int sum = nums[0];
      int left = 0;
      int right = 1;
      while (right < nums.length) {
        if (nums[right] >= target) {
          return 1;
        }
        sum += nums[right];
        if (sum >= target) {
          while (left < right && sum >= target) {
            sum -= nums[left];
            ++left;
          }
          answer = Math.min(right - left + 2, answer);
        }
        ++right;
      }
      return answer == Integer.MAX_VALUE ? 0 : answer;
    }
  }

}
